'use strict';
/**
 * Created by FreezeSoul on 2016/1/20.
 */
define([
    "app/core/base",
    "app/core/util",
    "../commonMeta",
    "jquery",
    "underscore",
    'JSONParse',
    'loglevel'
], function (Chart, Util, Meta, $, _, JSON, log) {

    var property = {
        config: "property",
        option: [
            {
                group: '基础',
                id: 'SelectTitleInfo',
                name: '标题',
                enable: false,
                type: 'text',
                value: '',
                default: '',
                link: 'SelectTitleInfo',
                tooltip: '标题'
            },
            {
                group: '基础',
                id: 'SelectDataValue',
                name: '下拉数据',
                enable: false,
                type: 'text',
                value: '',
                default: '',
                link: 'SelectDataValue',
                tooltip: '静态下拉数据，如：value1,text1;value2,text2'
            },
            {
                group: '基础',
                id: 'SelectTitleColor',
                name: '标题颜色',
                enable: false,
                type: 'color',
                value: '#000000',
                default: '#000000',
                link: 'SelectTitleColor',
                tooltip: '标题颜色'
            },
            {
                group: '基础',
                id: 'BackgroundColor',
                name: '背景颜色',
                enable: false,
                type: 'color',
                value: 'transparent',
                default: 'transparent',
                link: 'BackgroundColor',
                tooltip: '背景颜色，透明色transparent'
            },
            {
                group: '基础',
                id: 'ButtonTheme',
                name: '按钮皮肤',
                enable: false,
                type: 'select',
                value: 'default',
                default: 'default',
                data: [
                    {value: 'default', text: 'default'},
                    {value: 'danger', text: 'danger'},
                    {value: 'warning', text: 'warning'},
                    {value: 'primary', text: 'primary'},
                    {value: 'success', text: 'success'},
                    {value: 'info', text: 'info'}
                ],
                link: 'ButtonTheme',
                tooltip: '按钮皮肤'
            },
            {
                group: '绑定',
                id: 'selectDataBinding',
                name: '下拉绑定',
                enable: false,
                type: 'seriesBinding',
                dataset: '',
                dimension: '',
                measure: '',
                tooltip: '下拉绑定，文本绑定维度，值绑定度量'
            }, {
                group: '绑定',
                id: 'FilterName',
                name: '过滤列名称',
                enable: false,
                type: 'text',
                value: '',
                default: '',
                link: 'filterName',
                tooltip: '绑定数据集，客户端过滤字段列名称'
            },
            {
                group: '绑定',
                id: 'FilterValue',
                name: '过滤列默认值',
                enable: false,
                type: 'text',
                value: '',
                default: '',
                link: 'filterValue',
                tooltip: '绑定数据集，客户端过滤字段默认值'
            },
            {
                group: '事件',
                id: 'SelectClick',
                name: '下拉跳转事件',
                enable: true,
                type: 'pivotEvent',
                value: {
                    Event: "SelectClick",
                    Params: [
                        {Value: "SelectData", Name: "下拉选中值"}
                    ]
                },
                tooltip: '下拉跳转事件，钻取设置'
            }
        ].concat($.extend(true, [], Meta.commonProperties)),
        MapOption: function (option) {
            Util.linkOption(this.option, option);
        }
    };

    var select = Chart.extend({
        constructor: function (layout) {
            this._layout = layout;
            this._element = null;
            this._lastdata = null;
            this._container = null;
            this._option = {
                Series: [],
                Events: [],
                Extend: $.extend(true, {}, property),
                Option: {
                    uuid: '',
                    class: '',
                    display: true,
                    SelectTitleInfo: "范围选择",
                    SelectDataValue: '1,一月;2,二月;3,三月;4,四月;5,五月;6,六月;7,七月;8,八月;9,九月;10,十月;11,十一月;12,十二月',
                    BackgroundColor: 'transparent',
                    SelectTitleColor: '#000',
                    ButtonTheme: 'default',
                    initScript: '',
                    disposeScript: ''
                }
            };
        },
        init: function (element) {
            try {
                this._container = element;
            } catch (e) {
                log.error(e);
            }
        },
        _readProperty: function () {
            try {
                if (!this._option.Extend) return;
                Util.deepMapOption(property, this._option.Extend, this._option.Option);
            } catch (e) {
                log.error(e);
            }
        },
        _render: function (option) {
            $(this._container).empty();
            var $element = $('<div style="text-align:center;width: 100%;height: 100%;"><div style="margin: 15px;display:inline-block;">' +
                '<div class="title_div" style="margin: 5px; float:left;font-size: 16px;font-weight: bold;line-height: 34px;text-align: left;"></div>' +
                '<div class="select_div" style="float:left;margin: 5px;"> <select class="form-control" style="min-width: 220px;"></select></div>' +
                '<div class="btn_div" style="float:left;margin: 5px;"><button class="btn btn-sm">确定</button></div>' +
                '</div></div>');
            if (option.SelectTitleInfo) {
                $element.find(".title_div").show().text(option.SelectTitleInfo);
            } else {
                $element.find(".title_div").hide();
            }
            if (option.BackgroundColor) {
                $element.css("background", option.BackgroundColor);
            }
            if (option.SelectTitleColor) {
                $element.find(".title_div").css("color", option.SelectTitleColor);
            }
            if (option.ButtonTheme) {
                $element.find("button.btn").addClass("btn-" + option.ButtonTheme);
            } else {
                $element.find("button.btn").addClass("btn-default");
            }
            if (option.SelectDataValue) {
                var $select = $element.find(".select_div select");
                var dataStrArray = option.SelectDataValue.split(';');
                $.each(dataStrArray, function (i, dataStr) {
                    var dataArray = dataStr.split(',');
                    if (dataArray.length === 2) {
                        $select.append($("<option></option>")
                            .attr("value", dataArray[0])
                            .text(dataArray[1]));
                    }
                });
            }

            //本页面钻取后状态保留
            var values = this._pivotValues("SelectClick");
            if (values && values.length > 0) {
                var value = _.findWhere(values, {Value: "SelectData"});
                if (value) {
                    $select.val(value.ParamValue);
                }
            }

            $element.appendTo(this._container);

            this._bindEvent($element);

            //Util.setCommonMeta(this, this._container, this._option.Option);
            //Util.initChartLifeTime(this, this._container, this._option.Option);

            return $element;
        },
        _pivotValues: function (eventName) {
            var _this = this;
            var values = [];
            var registerEvent = _.findWhere(_this._option.Events, {Event: eventName});
            if (registerEvent) {
                values = registerEvent.Params;
                if (this._layout && this._layout.getParams) {
                    var params = this._layout.getParams();
                    $.each(params, function (i, param) {
                        var value = _.findWhere(values, {ParamName: param.ParamName});
                        if (value) {
                            value.ParamValue = param.ParamValue;
                        }
                    });
                }
            }
            return values;
        },
        _bindEvent: function (element) {
            var _this = this;
            $(element).find("button.btn").on("click", function (e) {
                if (_this._layout
                    && _this._layout.navigate
                    && _this._option.Events
                    && _this._option.Events.length > 0) {

                    var registerEvent = _.findWhere(_this._option.Events, {Event: "SelectClick"});
                    if (registerEvent) {
                        var pageId = registerEvent.PageId;
                        var params = registerEvent.Params;
                        var args = [];
                        var sParam = _.findWhere(params, {Value: "SelectData"});
                        if (sParam && sParam.ParamName) {
                            args.push({
                                ParamName: sParam.ParamName,
                                ParamValue: $(element).find('select option:selected').val()
                            });
                        }

                        _this._layout.navigate(pageId, args);
                    }
                    e.preventDefault();
                }
            });

            if (!this._filterDataHandle) {
                this._filterDataHandle = function (params) {
                    _this.filterDataHandle.call(_this, params);
                };
            }
            this._layout.removeListener("filterData", this._filterDataHandle);
            this._layout.addListener("filterData", this._filterDataHandle);
        },
        filterDataHandle: function (params) {
            var _this = this;
            var flag = false;
            var filterColumn = _.findWhere(this._option.Extend.option, {name: '过滤列名称'});
            var filterValue = _.findWhere(this._option.Extend.option, {name: '过滤列默认值'});

            if (filterColumn && filterValue
                && filterColumn.enable && filterValue.enable
                && filterColumn.value !== "" && filterValue.value !== ""
            ) {
                for (var prop in params) {
                    if (!params.hasOwnProperty(prop)) continue;
                    if (filterColumn.value === prop) {
                        filterValue.value = params[prop];
                        flag = true;
                    }
                }
            }
            if (flag && _this._lastdata) {
                _this.setData(_this._lastdata);
            }
        },
        example: function () {
            try {
                var exampleOption = {
                    SelectTitleInfo: "范围选择",
                    SelectDataValue: '1,一月;2,二月;3,三月;4,四月;5,五月;6,六月;7,七月;8,八月;9,九月;10,十月;11,十一月;12,十二月',
                    BackgroundColor: 'transparent',
                    SelectTitleColor: '#000',
                    ButtonTheme: 'default'
                };
                this._element = this._render(exampleOption);
            } catch (e) {
                log.error(e);
            }
        },
        _filterTable: function (option, table) {
            var filterColumn = _.findWhere(option, {name: '过滤列名称'});
            var filterValue = _.findWhere(option, {name: '过滤列默认值'});

            if (table && filterColumn && filterValue
                && filterColumn.enable && filterValue.enable
                && filterColumn.value !== "" && filterValue.value !== ""
            ) {
                var tableCopy = _.map(table, _.clone);
                return _.filter(tableCopy, function (row) {
                    return row[filterColumn.value] === filterValue.value;
                });
            }
            return table;
        },
        _bindData: function (data) {
            var _this = this;
            var bindProperty = _.findWhere(this._option.Extend.option, {type: 'seriesBinding'});
            if (!bindProperty || !bindProperty.dataset) return;
            var dataSetCode = bindProperty.dataset;
            var table = data[dataSetCode];
            table = this._filterTable(this._option.Extend.option, table);
            if (table && table.length > 0 && bindProperty.column) {
                var dimensionName = bindProperty.dimension.ColumnName;
                var measureName = bindProperty.measure.ColumnName;
                if (table && table.length > 0) {
                    _this._option.Option.SelectDataValue = [];
                    $.each(table, function (j, row) {
                        _this._option.Option.SelectDataValue.push(row[measureName] + ',' + row[dimensionName]);
                    });
                    _this._option.Option.SelectDataValue = _this._option.Option.SelectDataValue.join(';');
                }
            }
        },
        setData: function (data) {
            try {
                this._lastdata = data;

                this._readProperty();
                if (data
                    && this._option.Binding
                    && this._option.Binding.length > 0
                    && this._option.Extend
                ) {
                    this._bindData(data);
                }
                this._element = this._render(this._option.Option);
            } catch (e) {
                log.error(e);
            }
        },
        setOption: function (option) {
            try {
                return this._option = $.extend(true, {}, option);
            } catch (e) {
                log.error(e);
            }
        },
        getOption: function () {
            try {
                this._readProperty();
            } catch (e) {
                log.error(e);
            }
            return this._option;
        },
        setTheme: function (theme) {
            try {
            } catch (e) {
                log.error(e);
            }
        },
        resize: function () {
            try {
            } catch (e) {
                log.error(e);
            }
        },
        showLoading: function () {
            try {
                if (this._layout && this._layout.showLoading) {
                    this._layout.showLoading(this);
                }
            } catch (e) {
                log.error(e);
            }
        },
        hideLoading: function () {
            try {
                if (this._layout && this._layout.hideLoading) {
                    this._layout.hideLoading(this);
                }
            } catch (e) {
                log.error(e);
            }
        },
        dispose: function () {
            try {
                $(this._element).remove();
                this._layout.removeListener("filterData", this._filterDataHandle);
                //Util.disposeChartLifeTime(this, this._container, this._option.Option);

            } catch (e) {
                log.error(e);
            }
        },
        getElement: function () {
            return this._element;
        },
        getChart: function () {
            return this._element;
        }
    });

    return {
        Chart: select,
        Property: property
    };
});